import { Button, Card, Modal, Space, Table } from "antd";
import { ColumnsType } from "antd/lib/table";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import FormRender, { useForm, Error as FormRenderError } from "form-render";
import { createGroup, deleteGroup, getTaskCategoryList, useTaskRoot, updateGroup } from "../../api";

const categorySchema = {
  type: 'object',
  properties: {
    name: {
      title: '类别名称',
      type: 'string',
      required: true,
    },
    comments: {
      title: '类别说明',
      type: 'string',
      format: 'textarea',
    },
  },
};

interface ListProps { }

const List: React.FC<ListProps> = () => {
  const taskRoot = useTaskRoot();
  const [categoryList, setCategoryList] = useState<any[]>();
  const [currentItem, setCurrentItem] = useState<any>();

  // 获取任务根目录，更新任务类别列表
  useEffect(() => {
    (async () => setCategoryList(await getTaskCategoryList(taskRoot)))()
  }, [taskRoot]);

  const form = useForm();
  const [formModalTitle, setFormModalTitle] = useState<string>("");
  const [isFormModalOpen, setIsFormModalOpen] = useState<boolean>(false);

  const showFormModal = useCallback((item: any) => {
    setCurrentItem(item);

    form.resetFields();
    if (!item) {
      setFormModalTitle("新建类别");
    } else {
      setFormModalTitle("修改类别");
      const { component: { name, comments } } = item;
      form.setValues({ name, comments });
    }
    setIsFormModalOpen(true);
  }, [form]);

  const handleFormModalOk = useCallback(() => {
    form.submit();
  }, [form]);

  const handleFormModalCancel = useCallback(() => {
    setIsFormModalOpen(false);
  }, []);

  const onFormModalFinish = useCallback(async (formData: any, errors: FormRenderError[]) => {
    if (errors?.length) {
      return;
    }

    if (currentItem) {
      // update
      const category = await updateGroup(currentItem, formData);
      setCategoryList(categoryList?.map(item => item.id === currentItem.id ? category : item));
    } else {
      // create
      const category = await createGroup(taskRoot, formData);
      setCategoryList((categoryList && [...categoryList, category]) || [category]);
    }

    setIsFormModalOpen(false);
  }, [categoryList, currentItem, taskRoot]);

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);

  const showDeleteModal = useCallback((item: any) => {
    setCurrentItem(item);
    setIsDeleteModalOpen(true);
  }, []);

  const handleDeleteOk = useCallback(async () => {
    await deleteGroup(currentItem);
    setCategoryList(categoryList?.filter(item => item.id !== currentItem.id));
    setIsDeleteModalOpen(false);
  }, [categoryList, currentItem]);

  const handleDeleteCancel = useCallback(() => {
    setIsDeleteModalOpen(false);
  }, []);

  const tableColumns = useMemo<ColumnsType<any>>(() => [
    {
      title: "类别名称",
      key: "name",
      dataIndex: ["component", "name"],
      onHeaderCell: () => { return { style: { "fontWeight": "bold", "whiteSpace": "nowrap" } } },
      onCell: () => { return { style: { "minWidth": "12em" } } },
    },
    {
      title: "类别说明",
      key: "comments",
      dataIndex: ["component", "comments"],
      width: "100%",
      onHeaderCell: () => { return { style: { "fontWeight": "bold", "whiteSpace": "nowrap" } } },
    },
    {
      title: "操作",
      render: (item) => <Space size="small">
        <Button type="link" target="_blank" href={`/nifi/#/process-groups/${item.id}`}>打开</Button>
        <Button type="default" onClick={() => showFormModal(item)}>修改</Button>
        <Button type="default" onClick={() => showDeleteModal(item)} danger={true}>删除</Button>
      </Space>,
      onHeaderCell: () => { return { style: { "fontWeight": "bold", "whiteSpace": "nowrap" } } },
      onCell: () => { return { style: { "whiteSpace": "nowrap" } } },
    },
  ], [showDeleteModal, showFormModal]);

  return (
    <>
      <Card className="mb-16">
        <h1>任务类别</h1>
      </Card>
      <Card>
        <Space direction="vertical" style={{ 'display': 'flex' }}>
          <Button type="primary" onClick={() => showFormModal(null)}>新建</Button>
          <Table
            columns={tableColumns}
            rowKey="id"
            dataSource={categoryList}
            loading={!categoryList}
          />
        </Space>
        <Modal title={formModalTitle} visible={isFormModalOpen} onOk={handleFormModalOk} onCancel={handleFormModalCancel}>
          <FormRender form={form} schema={categorySchema} onFinish={onFormModalFinish} />
        </Modal>
        <Modal title="删除类别" visible={isDeleteModalOpen} onOk={handleDeleteOk} onCancel={handleDeleteCancel}>
          <p>您正在删除：</p>
          <p>类别名称：{currentItem?.component.name}</p>
          <p>类别说明：{currentItem?.component.comments}</p>
        </Modal>
      </Card>
    </>
  );
};

export default List;
